package cn.xorange.commons.system.controller.platform;


import cn.xorange.commons.core.basic.bean.ResultBean;
import cn.xorange.commons.core.basic.bean.SystemCode;
import cn.xorange.commons.core.basic.controller.DataController;
import cn.xorange.commons.security.annotation.Authorize;
import cn.xorange.commons.system.entity.platform.SysProduct;
import cn.xorange.commons.system.service.platform.ISysProductService;
import cn.xorange.commons.system.service.platform.ISysProductSpuService;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2024/6/25
 * description :
 */
@RestController
@Authorize(hasPerm = "platform:product")
@RequestMapping("/platform/product")
public class SysProductController extends DataController<SysProduct, ISysProductService> {

    @Resource
    ISysProductSpuService productSpuService;

    @Authorize(hasPerm = "list")
    @GetMapping("/options")
    public ResultBean options(SysProduct SysProduct){
        SysProduct.selectColumn("productId","productName","remark");
        return ResultBean.onSuccess(this.service.getList(SysProduct));
    }


    @Override
    @Authorize(hasPerm = "remove")
    @DeleteMapping("/{productId}")
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultBean del(@PathVariable Long productId){
        int num = this.service.getProductMenuNum(productId);
        if(num>0){
            return ResultBean.onFail("该产品下有在用功能");
        }
        int n = productSpuService.checkSpuByDefaultProductId(productId);
        if(n>0){
            return ResultBean.onFail("该产品存在SPU默认绑定");
        }
        this.service.deleteById(productId);
        return ResultBean.onSuccess();
    }

    @GetMapping("/menuIds/{productId}")
    public ResultBean getSysProductMenuIds(@PathVariable(value = "productId") Long productId){
        return ResultBean.onSuccess(this.service.getProductMenuIds(productId));
    }

    @Authorize(hasPerm = "setMenuIds")
    @PostMapping("/menuIds")
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultBean setSysProductMenuIds(@RequestBody SysProduct sysProduct){
        JSONArray menuIds = sysProduct.getParams().getJSONArray("menuIds");
        if (Objects.isNull(sysProduct.getProductId()) || Objects.isNull(menuIds)){
            return ResultBean.onFail(SystemCode.SYSTEM_PARAM_EXCEPTION);
        }else {
            this.service.setProductMenus(sysProduct.getProductId(), menuIds);
            return ResultBean.onSuccess();
        }
    }
}
